import { useEffect, useState } from 'react';
import { Popover, Space } from 'antd';
import {
  AlphaPicker,
  BlockPicker,
  ChromePicker,
  CirclePicker,
  CompactPicker,
  GithubPicker,
  HuePicker,
  MaterialPicker,
  PhotoshopPicker,
  SketchPicker,
  SliderPicker,
  SwatchesPicker,
  TwitterPicker,
} from 'react-color';
//@ts-ignore
import tinycolor from 'tinycolor2';

import styles from './index.less';

const PICKER = {
  AlphaPicker,
  BlockPicker,
  ChromePicker,
  CirclePicker,
  CompactPicker,
  GithubPicker,
  HuePicker,
  MaterialPicker,
  PhotoshopPicker,
  SketchPicker,
  SliderPicker,
  SwatchesPicker,
  TwitterPicker,
};

type ColorType = 'hex' | 'hsl' | 'hsv' | 'oldHue' | 'rgb';

interface IColorPickerProps {
  type?: keyof typeof PICKER;
  value?: string;
  colorType?: ColorType;
  pickerProps?: any;
  readonly?: boolean;
  showText?: boolean;
  onChange?: (color: string) => void;
}

const colorFormat = (colorMap: any, type: ColorType) => {
  switch (type) {
    case 'hex':
      return tinycolor(colorMap.hex).setAlpha(colorMap.rgb.a).toHex8String();
    case 'hsl':
      const hsl = colorMap.hsl;
      return tinycolor.fromRatio(hsl).toHslString();
    case 'rgb':
      const rgb = colorMap.rgb;
      return tinycolor.fromRatio(rgb).toRgbString();
    default:
      return '';
  }
};

const ColorPicker: React.FunctionComponent<IColorPickerProps> = (props) => {
  const { type, value, colorType, pickerProps = {}, readonly, showText, onChange } = props;
  const [color, setColor] = useState('rgb(255, 255, 255)');

  const Picker = PICKER[type || 'ChromePicker'] || PICKER.SketchPicker;

  useEffect(() => {
    if (!value && !tinycolor(value).isValid()) return;
    const newValue = tinycolor(value).toString(colorType || 'rgb');
    setColor(newValue!);
  }, [value, colorType]);

  const onCompleteHandle = (cm: any) => {
    const c = colorFormat(cm, colorType || 'rgb');
    setColor(c);
    onChange?.(c);
  };
  const open = !readonly ? {} : { open: false };

  return (
    <Space className={styles['picker-wrapper']}>
      <Popover
        {...open}
        placement="bottom"
        title={false}
        autoAdjustOverflow
        content={
          <Picker width={250} color={color} onChangeComplete={onCompleteHandle} {...pickerProps} />
        }
        trigger="hover"
      >
        <div className={styles['color-btn']} style={{ backgroundColor: color }} />
      </Popover>

      {showText && <div className={styles['color-input']}>{color}</div>}
    </Space>
  );
};

export default ColorPicker;
